<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">结算时间</label>
                            <div class="layui-input-inline">
                                <input type="text" autocomplete="off" name="timePeriod" id="timePeriod"
                                       class="layui-input"
                                       placeholder="请选择时间段">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-warm layui-btn-sm data-add-btn" lay-event="exportBtn"> 导出</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" style="display: none"
                        id="releaseProceedsBtn" lay-event="releaseProceeds"> 发放收益
                </button>
                <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                        id="text-show-btn"></button>
            </div>
        </script>

        <script type="text/html" id="currentTableBar">
            {{# if(d.status == "已结算"){ }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs data-count-edit">已发放</a>
            {{# }else{ }}
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="releaseProceeds">发放收益</a>
            {{# } }}
        </script>

        <table class="layui-hide" id="revenueRecordsTableId" lay-filter="currentTableFilter"></table>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script>

    let isShowBtn = false;

    let colList = [];

    layui.use(['form', 'table', 'laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            laydate = layui.laydate;

        // 初始化日期选择器
        laydate.render({
            elem: '#timePeriod',
            type: 'month', //选择器类型，只显示年月
            format: 'yyyy-MM-dd', //日期格式
            value: new Date(),
            max: 'now',
        });


        const requestData = {
            btnRoles: {
                "btn-1": 'admin'
            },
        }
        $.ajax({
            type: "POST",
            url: '/role/checkUserRole',
            data: JSON.stringify(requestData),
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            success: function (req) {
                if (req.code === '200') {
                    // 判断是是否查询的月份是上个月份
                    timeCoincides();
                    let btnRoles = req.data?.btnRoles;
                    if (isShowBtn === true) {
                        isShowBtn = btnRoles["btn-1"];
                    }
                    table.render({
                        elem: '#revenueRecordsTableId',
                        url: '/revenueRecords/list',
                        parseData: function (res) { //res 即为原始返回的数据
                            let data = res.data;
                            let textShowBtn = document.getElementById("text-show-btn");
                            let dateStr = $('#timePeriod').val();
                            let targetDate;
                            if (isNotNull(dateStr)) {
                                targetDate = new Date(dateStr);
                            } else {
                                targetDate = new Date();
                            }
                            textShowBtn.innerText = targetDate.getFullYear() + '年' + (targetDate.getMonth() + 1) + '月' + '累计收益总额' + data?.totalAccumulatedIncome + '元'
                            return {
                                "code": res.code, //解析接口状态
                                "msg": res.msg, //解析提示文本
                                "count": data.total, //解析数据长度
                                "data": data.list //解析数据列表
                            };
                        },
                        method: 'GET',
                        contentType: 'application/x-www-form-urlencoded',
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['filter', 'exports', 'print', {
                            title: '提示',
                            layEvent: 'LAYTABLE_TIPS',
                            icon: 'layui-icon-tips'
                        }],
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {
                                field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                                    return d.LAY_INDEX; //返回序号
                                }
                            },
                            {field: 'providerId', title: '编号', sort: true, align: 'center'},
                            {field: 'nickName', title: '服务商昵称', sort: true, align: 'center'},
                            {field: 'area', title: '所在地区', sort: true, align: 'center'},
                            {field: 'street', title: '所在街道', sort: true, align: 'center'},
                            {field: 'storeName', title: '店铺名称', sort: true, align: 'center'},
                            {field: 'phone', title: '手机号', sort: true, align: 'center'},
                            {field: 'bindOfficialAccount', title: '绑定公众号', sort: true, align: 'center'},
                            {field: 'orderQuantity', title: '订单量', sort: true, align: 'center'},
                            {field: 'accumulatedIncome', title: '累计收益', sort: true, align: 'center'},
                            {field: 'lastJoinTime', title: '更新时间', sort: true, align: 'center'},
                            {
                                title: '操作',
                                toolbar: '#currentTableBar',
                                hide: !isShowBtn,
                                align: 'center'
                            }
                        ]],
                        limits: [50, 100, 150, 200, 250, 300],
                        limit: 50,
                        page: true,
                        request: {
                            pageName: 'pageNum',
                            limitName: 'pageSize'
                        },
                        response: { //定义后端 json 格式，详细参见官方文档
                            statusName: 'code', //状态字段名称
                            statusCode: '200', //状态字段成功值
                            msgName: 'msg', //消息字段
                            countName: 'count', //总数字段
                            dataName: 'data' //数据字段
                        },
                        done: function () {
                            colList = this.cols
                        }
                    });
                    showBtn();
                }
            },
            error: function (e) {
                layer.msg(e.msg);
            }
        })

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            let date;
            if (isNotNull(data.field.timePeriod)) {
                date = new Date(data.field.timePeriod);
            } else {
                date = new Date();
            }
            // 获取下一个月的第一天
            let nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
            // 获取当前月份的最后一天
            let lastDayOfMonth = new Date(nextMonth.getTime() - 1);
            // 格式化日期字符串为yyyy-MM-dd
            let formattedDate = lastDayOfMonth.getFullYear() + '-' + (lastDayOfMonth.getMonth() + 1).toString().padStart(2, '0') + '-' + lastDayOfMonth.getDate().toString().padStart(2, '0');
            timeCoincides();
            let cols = colList[0];
            for (let col of cols) {
                if (col.title === '操作') {
                    col.hide = !isShowBtn;
                }
            }
            table.reload('revenueRecordsTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    timePeriod: formattedDate
                },
                done: function (res, curr, count) {
                    showBtn();
                }
            }, 'data');
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'exportBtn') {  // 监听导出操作
                let ids = [];
                let dataList = table.checkStatus('revenueRecordsTableId')?.data;
                if (dataList.length !== 0) {
                    dataList.forEach(function (item) {
                        ids.push(item.id)
                    });
                }
                const data = {
                    // 拿到当前的搜索内容的条件
                    timePeriod: obj.config?.where?.timePeriod,
                    ids: ids
                }
                // 判断是不是多选
                downloadExcel('/revenueRecords/export/list', data, '区域服务商收益记录.xlsx', 'POST')
                return false;
            } else if (obj.event === 'releaseProceeds') {
                var checkStatus = table.checkStatus('revenueRecordsTableId');
                if (checkStatus?.data.length === 0) {
                    // 处理请求失败后的操作
                    layer.msg("请至少选中一行数据");
                    return;
                }
                var index = layer.alert("是否发放选择的区域服务商收益？", {
                    title: '提示'
                }, function () {
                    let myMsg = layer.msg("正在提交...", {
                        icon: 16,
                        time: -1
                    })
                    let requestData = {
                        ids: [],
                        batchType: 0,
                        timePeriod: obj.config?.where?.timePeriod,
                    }
                    if (checkStatus.isAll) {
                        requestData.batchType = 1;
                    } else {
                        var dataList = checkStatus.data;
                        let ids = [];
                        dataList.forEach(function (item) {
                            ids.push(item.id)
                        });
                        requestData.ids = ids;
                    }
                    $.ajax({
                        url: "/revenueRecords/incomeDistribution",
                        method: "POST",
                        dataType: 'json',
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        success: function (result) {
                            if (result.code === '200') {
                                layer.msg("收益发放成功")
                                reloadTable();
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            // 处理请求失败后的操作
                            layer.msg("请求失败：" + error);
                        }
                    });
                });
            }
            return false;
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'releaseProceeds') {

                let ids = [];
                ids.push(data?.id)
                if (ids.length === 0) {
                    layer.msg("数据异常，请联系系统管理员");
                    return;
                }
                var index = layer.alert("是否发放选择的区域服务商收益？", {
                    title: '提示'
                }, function () {
                    let myMsg = layer.msg("正在提交...", {
                        icon: 16,
                        time: -1
                    })
                    let requestData = {
                        ids: ids,
                        batchType: 1,
                    }
                    $.ajax({
                        url: "/revenueRecords/incomeDistribution",
                        method: "POST",
                        dataType: 'json',
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        success: function (result) {
                            if (result.code === '200') {
                                layer.msg("收益发放成功")
                                reloadTable();
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            // 处理请求失败后的操作
                            layer.msg("请求失败：" + error);
                        }
                    });
                });
            }
            return false;
        });
    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('revenueRecordsTableId', {
                url: '/revenueRecords/list',
                done: function (res, curr, count) {
                    showBtn();
                }
            });
        })
    }

    function timeCoincides() {
        layui.use(['form', 'table', 'laydate'], function () {
            var $ = layui.jquery;
            // 判断当前月份
            // 判断月份
            const currentDate = new Date();
            currentDate.setMonth(currentDate.getMonth() - 1);
            let dateStr = $('#timePeriod').val()
            const targetDate = new Date(dateStr);
            if (currentDate.getMonth() === targetDate.getMonth()) {
                isShowBtn = true;
            } else {
                isShowBtn = false;
            }
        });
    }

    function showBtn() {
        let releaseProceedsBtn = document.getElementById("releaseProceedsBtn");
        if (isShowBtn === true) {
            releaseProceedsBtn.style.display = '';
        } else {
            releaseProceedsBtn.style.display = 'none';
        }
    }
</script>

</body>
<style>
    .text-show-btn {
        border: none;
        font-size: 14px;
        color: red;
    }

    .text-show-btn:hover {
        color: red;
    }
</style>
</html>
